package com.hh.fudan.project_management;

import java.util.Timer;

import com.hh.fudan.project_management.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.IBinder;
import android.test.NotificationResult;
import android.test.NotificationSpider;
import android.widget.Toast;

public class NotificationService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	int x = 0;

	public Timer timer;

	@Override
	public void onCreate() {
		Toast.makeText(NotificationService.this, "Created:", Toast.LENGTH_SHORT);
		System.out.println("created " + x);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		System.out.println("Notification Start");
		start();
	}

	public void start() {
		timer = new Timer();
		System.out.println("timer start");
		SharedPreferences prefs = getSharedPreferences("usersettings", 0);
		timer.scheduleAtFixedRate(new NotificationSpider(this, prefs), 0, 60000);
	}

	@Override
	public void onDestroy() {
		timer.cancel();
	}

	public void addNotification(NotificationResult result) {

		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		if (result == null)
			return;
		int icon = R.drawable.icon;
		CharSequence tickerText = "一盒团为您发现了" + result.getNum() + "条新团购";
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);

		Context context = getApplicationContext();
		CharSequence contentTitle = "一盒团为您发现了" + result.getNum() + "条新团购，其中"
				+ result.getNearbyNum() + "条的商店在您的常用地点附近";
		CharSequence contentText = result.getContents();

		Intent notificationIntent = new Intent();

		notificationIntent.setClass(NotificationService.this,
				GroupShoppingActivity.class);
		notificationIntent.setData(Uri.parse("notif"));
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.contentIntent = contentIntent;
		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);
		if (result.getNum() > 0) {
			mNotificationManager.notify(0, notification);

			this.updatePreferences(result);
		} else {
			mNotificationManager.cancel(0);
		}
	}

	public void updatePreferences(NotificationResult result) {
		SharedPreferences prefs = getSharedPreferences("usersettings", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putInt("num", result.getNum());
		editor.putInt("nearbyNum", result.getNearbyNum());
	}
}
